import {
  getMemberAddressByIdAPI,
  postMemberAddressAPI,
  putMemberAddressByIdAPI,
} from '@/services/address'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

const useAddFromHooks = () => {
  let id = ''
  // 表单数据
  const form = ref({
    receiver: '', // 收货人
    contact: '', // 联系方式
    fullLocation: '', // 省市区(前端展示)
    provinceCode: '', // 省份编码(后端参数)
    cityCode: '', // 城市编码(后端参数)
    countyCode: '', // 区/县编码(后端参数)
    address: '', // 详细地址
    isDefault: 0, // 默认地址，1为是，0为否
  })

  // 获取收货地址详情数据
  const getMemberAddressByIdData = async () => {
    if (id) {
      // 发送请求
      const res = await getMemberAddressByIdAPI(id)
      // 把数据合并到表单中
      Object.assign(form.value, res.result)
    }
  }

  // 收集所在地区
  const onRegionChange: UniHelper.RegionPickerOnChange = (ev) => {
    // 省市区(前端展示)
    form.value.fullLocation = ev.detail.value.join(' ')
    // 省市区(后端参数)
    const [provinceCode, cityCode, countyCode] = ev.detail.code!
    Object.assign(form.value, { provinceCode, cityCode, countyCode })
  }

  // 收集是否默认收货地址
  const onSwitchChange: UniHelper.SwitchOnChange = (ev) => {
    form.value.isDefault = ev.detail.value ? 1 : 0
  }

  // 定义校验规则
  const rules = {
    receiver: {
      rules: [{ required: true, errorMessage: '请输入收货人姓名' }],
    },
    contact: {
      rules: [
        { required: true, errorMessage: '请输入联系方式' },
        { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
      ],
    },
    countyCode: {
      rules: [{ required: true, errorMessage: '请选择所在地区' }],
    },
    address: {
      rules: [{ required: true, errorMessage: '请选择详细地址' }],
    },
  }

  // 表单组件实例
  const formRef = ref()

  // 提交表单
  const onSubmit = async () => {
    try {
      // 表单校验
      await formRef.value?.validate?.()
      // 校验通过后再发送请求
      if (id) {
        // 修改地址请求
        await putMemberAddressByIdAPI(id, form.value)
      } else {
        // 新建地址请求
        await postMemberAddressAPI(form.value)
      }
      // 成功提示
      uni.showToast({ icon: 'success', title: id ? '修改成功' : '添加成功' })
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 400)
    } catch (error) {
      uni.showToast({ icon: 'error', title: '请填写完整信息' })
    }
  }

  // 页面加载
  onLoad((options) => {
    id = options!.id
    // 动态设置标题
    uni.setNavigationBarTitle({ title: id ? '修改地址' : '新建地址' })
    getMemberAddressByIdData()
  })

  return { rules, form, formRef, onRegionChange, onSwitchChange, onSubmit }
}

export default useAddFromHooks
